package cn.edu.hqu.javaee.spring_securing_web.MyUserDetailsService;

import cn.edu.hqu.javaee.spring_securing_web.Service.SysUserService;
import cn.edu.hqu.javaee.spring_securing_web.SysUser.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;


@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        // 从数据库中取出用户信息
        SysUser user = userService.selectByName(username);

        // 判断用户是否存在
        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
//        String password = user.getPassword();
//        String encode = new BCryptPasswordEncoder().encode(password);


        // 返回UserDetails实现类
        return new User(user.getName(),user.getPassword(), authorities);
    }
}
